<?php

namespace App\Http\ApiControllers;

use App\Facades\Api;
use App\Http\Requests\CommentRequest;
use App\Http\Resources\CommentCollection;
use App\Models\Player;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class CommentController extends ApiController
{
    public function index(Player $player): JsonResponse
    {
        $list = $player->comments()
            ->latest()
            ->paginate();

        return $this->success(new CommentCollection($list));
    }

    public function store(CommentRequest $request, Player $player): JsonResponse
    {
        try {
            $this->verifyCaptcha();

            if ($player->season->config['show_captcha']) {
                $validator = Validator::make($request->all(), [
                    'content' => 'required|bail|string|min:5|max:200',
                ], [
                    'content.required' => '评论内容必须填写',
                    'content.string' => '评论内容必须填写',
                    'content.min' => '评论内容最低为:min个字',
                    'content.max' => '评论内容最多为:max个字',
                ]);

                if ($validator->fails()) {
                    throw new Exception($validator->errors()->first());
                }
            }

            $player->giveComment(Api::user(), $request->post('content'));

            return $this->success();
        } catch (Exception $e) {
            return $this->failed($e->getMessage(), $e->getCode());
        }
    }
}
